<?php
/**
 * This is the model class for table "{{%article}}".
 *
 * @property integer $id
 * @property integer $cid
 * @property integer $type
 * @property string $title
 * @property string $sub_title
 * @property string $summary
 * @property string $thumb
 * @property string $seo_title
 * @property string $seo_keywords
 * @property string $seo_description
 * @property integer $status
 * @property integer $sort
 * @property integer $author_id
 * @property string $author_name
 * @property integer $scan_count
 * @property integer $comment_count
 * @property integer $can_comment
 * @property integer $visibility
 * @property string $password
 * @property integer $flag_headline
 * @property integer $flag_recommend
 * @property integer $flag_slide_show
 * @property integer $flag_special_recommend
 * @property integer $flag_roll
 * @property integer $flag_bold
 * @property integer $flag_picture
 * @property string  $template
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property ArticleContent[] $articleContents
 */

class DownloadController extends BackendController
{

    /**
     * 显示详细内容
     * @param $id
     * @throws CHttpException
     */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

    /**
     * 创建内容
     */
	public function actionCreate()
	{
		$model=new Article;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{

            $_POST['Article']['type'] = Article::DOWNLOAD;
			$model->attributes = $_POST['Article'];

            //缩微图更新
            $file = CUploadedFile::getInstance($model, 'thumb'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $model->thumb = XUpload::createFile($file,'');
            }

            //封面图更新
            $coverFile = CUploadedFile::getInstance($model, 'cover'); //获得一个CUploadedFile的实例
            if ($coverFile) { // 判断实例化是否成功
                $model->cover = XUpload::createFile($coverFile,'');
            }

            //组图更新
            $images = XUpload::uploadMultiFile($model,'images');
            if($images) {
                $model->images=implode(",", $images);
            }

			if($model->save()){
                Yii::app()->user->setFlash('success', Yii::t('app', 'Create Success'));
                $this->redirect(array('index'));
            }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

    /**
     * 更新内容
     * @param $id
     * @throws CHttpException
     */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $thumb = $model->thumb; //取出数据库中缩微图
        $cover = $model->cover; //取出数据库中封面图
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];

			//缩微图更新
            $file = CUploadedFile::getInstance($model, 'thumb'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $model->thumb = XUpload::createFile($file, $thumb);
            }

            //封面图更新
            $coverFile = CUploadedFile::getInstance($model, 'cover'); //获得一个CUploadedFile的实例
            if ($coverFile) { // 判断实例化是否成功
                $model->cover = XUpload::createFile($coverFile, $cover);
            }

            //组图更新
            //判断是否删除所有组图，如果删除则为空
            if(isset($_POST['Article']['images']))
                $oldImages = implode(',',$_POST['Article']['images']);
            else
                $oldImages = '';
            $images = XUpload::uploadMultiFile($model,'images');
            if($images) {
                //历史图片 + 新增上传图片
                $model->images = $oldImages.','.implode(",", $images);
            }else{
                $model->images = $oldImages;
            }

			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Update Success'));
				$this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

    /**
     * 删除内容
     * @param $id
     * @throws CDbException
     * @throws CHttpException
     */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

    /**
     * 批量删除内容
     * @param $id
     * @throws CDbException
     * @throws CHttpException
     */
    public function actionDeleteAll()
    {
        $request = Yii::app()->request;
        if (!$request->isAjaxRequest || !$request->isPostRequest)
            return;

        $ids = $_POST['selection'];
        $criteria = new CDbCriteria;
        $criteria->addInCondition('id', $ids);
        if (Article::model()->deleteAll($criteria))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
            echo CJSON::encode(['result' => true]);
    }

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria = new CDbCriteria();
        $criteria->order = 'id DESC';
        $criteria->condition = 'type = '.Article::DOWNLOAD;
        $count = Article::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 14;
        $pages->applyLimit($criteria);
        $list = Article::model()->findAll($criteria);
        $this->render('index', array('count'=>$count,'list' => $list, 'pages' => $pages));

	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article']))
			$model->attributes=$_GET['Article'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Article the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Article $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

    /**
     * 删除图片
     */
    public function actionFileRemove() {
        if(isset($_POST)){
            $fileUrl = $_POST['fileUrl'];
            try {
                if ( !$fileUrl )
                    throw new Exception( "文件不存在" );
                $deleteFile = Yii::app()->basePath . '/../' . $fileUrl;
                if (file_exists($deleteFile))
                    unlink($deleteFile);
                $var['state'] = 'success';
                $var['message'] = '删除完成';
            } catch ( Exception $e ) {
                $var['state'] = 'errro';
                $var['message'] = '失败：'.$e->getMessage();
            }
            exit( CJSON::encode( $var ) );
        }
    }

}
